<?php
require_once __DIR__ . '/functions.php';

// 检查登录
if (!isLoggedIn()) {
    redirect('index.php', '请先登录', 'warning');
}

$userInfo = getUserInfo();
$orderId = intval($_GET['id'] ?? 0);

if ($orderId <= 0) {
    redirect('orders.php', '订单ID无效', 'danger');
}

// 获取订单信息，确保是当前用户的
$db = getDB();
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
$stmt->execute([$orderId, $userInfo['id']]);
$order = $stmt->fetch();

if (!$order) {
    redirect('orders.php', '订单不存在或无权限', 'danger');
}

// 检查订单是否已结算（结了本金或本金+佣金）
if ($order['settlement_type'] == 'principal' || $order['settlement_type'] == 'principal_commission') {
    redirect('orders.php', '订单已结算，无法修改', 'danger');
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $product_name = trim($_POST['product_name'] ?? '');
    $delivery_location = $_POST['delivery_location'] ?? '';
    $order_platform = $_POST['order_platform'] ?? '';
    $tracking_no = trim($_POST['tracking_no'] ?? '');
    $order_amount = floatval($_POST['order_amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'owner_paid';
    $notes = trim($_POST['notes'] ?? '');
    $pickup_code = trim($_POST['pickup_code'] ?? '');
    $is_signed = isset($_POST['is_signed']) ? intval($_POST['is_signed']) : 0;
    
    // 验证必填字段
    $errors = [];
    
    if (empty($product_name)) {
        $errors[] = '商品名称不能为空';
    }
    
    if (empty($delivery_location)) {
        $errors[] = '请选择收货地';
    }
    
    if (empty($order_platform)) {
        $errors[] = '请选择下单平台';
    }
    
    if (empty($tracking_no)) {
        $errors[] = '物流单号不能为空';
    }
    
    if ($order_amount <= 0) {
        $errors[] = '下单金额必须大于0';
    }
    
    if (strlen($product_name) > 200) {
        $errors[] = '商品名称长度不能超过200个字符';
    }
    
    if (strlen($tracking_no) > 18) {
        $errors[] = '物流单号长度不能超过18个字符';
    }
    
    if (strlen($notes) > 1000) {
        $errors[] = '备注信息长度不能超过1000个字符';
    }
    
    if (strlen($pickup_code) > 50) {
        $errors[] = '取件码长度不能超过50个字符';
    }
    
    // 处理文件上传
    $order_screenshot = $order['order_screenshot'];
    if (isset($_FILES['order_screenshot']) && $_FILES['order_screenshot']['error'] === UPLOAD_ERR_OK) {
        $uploadResult = uploadFile($_FILES['order_screenshot'], 'order_screenshot');
        if ($uploadResult['success']) {
            // 删除旧图片
            if ($order_screenshot) {
                deleteFile($order_screenshot, 'order_screenshot');
            }
            $order_screenshot = $uploadResult['filename'];
        } else {
            $errors[] = '图片上传失败: ' . $uploadResult['message'];
        }
    }
    
    if (empty($errors)) {
        // 更新订单 - 更新所有字段
        $stmt = $db->prepare("UPDATE orders SET 
                            product_name = ?,
                            delivery_location = ?,
                            order_platform = ?,
                            tracking_no = ?,
                            order_amount = ?,
                            payment_method = ?,
                            notes = ?,
                            order_screenshot = ?,
                            pickup_code = ?,
                            is_signed = ?,
                            updated_at = NOW()
                            WHERE id = ? AND user_id = ?");
        
        if ($stmt->execute([
            $product_name, 
            $delivery_location, 
            $order_platform, 
            $tracking_no, 
            $order_amount, 
            $payment_method, 
            $notes, 
            $order_screenshot, 
            $pickup_code, 
            $is_signed, 
            $orderId, 
            $userInfo['id']
        ])) {
            $success = '订单修改成功';
            // 更新本地订单数据
            $order = array_merge($order, [
                'product_name' => $product_name,
                'delivery_location' => $delivery_location,
                'order_platform' => $order_platform,
                'tracking_no' => $tracking_no,
                'order_amount' => $order_amount,
                'payment_method' => $payment_method,
                'notes' => $notes,
                'order_screenshot' => $order_screenshot,
                'pickup_code' => $pickup_code,
                'is_signed' => $is_signed
            ]);
            // 延迟跳转
            header("refresh:2;url=orders.php");
        } else {
            $error = '订单修改失败';
        }
    } else {
        $error = implode('<br>', $errors);
    }
}

// 获取配置选项
$delivery_locations = getConfigOptions('delivery_location');
$order_platforms = getConfigOptions('order_platform');

include __DIR__ . '/header.php';
?>

<div class="container">
    <div class="row">
        <div class="col-lg-10 offset-lg-1">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="bi bi-pencil-square text-primary"></i> 修改订单信息
                </h2>
                <a href="orders.php" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> 返回订单列表
                </a>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card">
                <div class="card-body">
                    <form method="POST" class="needs-validation" novalidate enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="product_name" class="form-label">
                                    <i class="bi bi-box text-primary"></i> 商品名称 <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="product_name" name="product_name" 
                                       value="<?php echo htmlspecialchars($order['product_name']); ?>" 
                                       placeholder="请输入商品名称" required maxlength="200">
                                <div class="invalid-feedback">请输入商品名称</div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="delivery_location" class="form-label">
                                    <i class="bi bi-geo-alt text-primary"></i> 收货地 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="delivery_location" name="delivery_location" required>
                                    <option value="">请选择收货地</option>
                                    <?php foreach ($delivery_locations as $location): ?>
                                        <option value="<?php echo htmlspecialchars($location['option_value']); ?>" 
                                            <?php echo $order['delivery_location'] == $location['option_value'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($location['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">请选择收货地</div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="order_platform" class="form-label">
                                    <i class="bi bi-shop text-primary"></i> 下单平台 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="order_platform" name="order_platform" required>
                                    <option value="">请选择下单平台</option>
                                    <?php foreach ($order_platforms as $platform): ?>
                                        <option value="<?php echo htmlspecialchars($platform['option_value']); ?>" 
                                            <?php echo $order['order_platform'] == $platform['option_value'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($platform['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">请选择下单平台</div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="tracking_no" class="form-label">
                                    <i class="bi bi-truck text-primary"></i> 物流单号 <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="tracking_no" name="tracking_no" 
                                       value="<?php echo htmlspecialchars($order['tracking_no']); ?>" 
                                       placeholder="请输入物流单号" required maxlength="100">
                                <div class="invalid-feedback">请输入物流单号</div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="order_amount" class="form-label">
                                    <i class="bi bi-currency-yen text-primary"></i> 下单金额 <span class="text-danger">*</span>
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text">¥</span>
                                    <input type="number" class="form-control" id="order_amount" name="order_amount" 
                                           value="<?php echo htmlspecialchars($order['order_amount']); ?>" 
                                           step="0.01" min="0.01" placeholder="0.00" required>
                                </div>
                                <div class="invalid-feedback">请输入有效的下单金额</div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="payment_method" class="form-label">
                                    <i class="bi bi-credit-card text-primary"></i> 付款方式 <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="payment_method" name="payment_method" required>
                                    <option value="owner_paid" <?php echo $order['payment_method'] == 'owner_paid' ? 'selected' : ''; ?>>自己付款</option>
                                    <option value="group_paid" <?php echo $order['payment_method'] == 'group_paid' ? 'selected' : ''; ?>>群主垫付</option>
                                </select>
                                <div class="invalid-feedback">请选择付款方式</div>
                            </div>
                        </div>

                        <!-- 可修改的字段 -->
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="pickup_code" class="form-label">
                                    <i class="bi bi-key text-primary"></i> 取件码
                                </label>
                                <input type="text" class="form-control" id="pickup_code" name="pickup_code" 
                                       value="<?php echo htmlspecialchars($order['pickup_code'] ?? ''); ?>" 
                                       placeholder="请输入取件码" maxlength="50">
                                <div class="form-text">
                                    到货后如果有取件码请在此填写
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="is_signed" class="form-label">
                                    <i class="bi bi-truck text-primary"></i> 是否签收
                                </label>
                                <select class="form-select" id="is_signed" name="is_signed">
                                    <option value="0" <?php echo $order['is_signed'] == 0 ? 'selected' : ''; ?>>未签收</option>
                                    <option value="1" <?php echo $order['is_signed'] == 1 ? 'selected' : ''; ?>>已签收</option>
                                </select>
                                <div class="form-text">
                                    请选择货物是否已被收货地签收
                                </div>
                            </div>
                        </div>
                        
                        <!-- 备注信息 -->
                        <div class="mb-3">
                            <label for="notes" class="form-label">
                                <i class="bi bi-sticky text-primary"></i> 备注信息
                            </label>
                            <textarea class="form-control" id="notes" name="notes" rows="3" 
                                      placeholder="请输入备注信息（可选）" maxlength="1000"><?php echo htmlspecialchars($order['notes'] ?? ''); ?></textarea>
                            <div class="form-text">最多1000个字符</div>
                        </div>
                        
                        <!-- 订单截图 -->
                        <div class="mb-3">
                            <label for="order_screenshot" class="form-label">
                                <i class="bi bi-image text-primary"></i> 订单截图
                            </label>
                            <input type="file" class="form-control" id="order_screenshot" name="order_screenshot" 
                                   accept="image/jpeg,image/png,image/gif,image/webp">
                            <div class="form-text">支持 JPG、PNG、GIF、WEBP 格式，最大 5MB</div>
                            
                            <?php if ($order['order_screenshot']): ?>
                                <div class="mt-2">
                                    <label class="form-label">当前截图：</label>
                                    <div>
                                        <img src="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                                             class="img-thumbnail" style="max-height: 200px; cursor: pointer;"
                                             onclick="openImageModal('<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>')">
                                        <div class="form-text">点击图片查看大图</div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="text-end">
                            <button type="button" class="btn btn-secondary" onclick="history.back()">取消</button>
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="bi bi-save"></i> 保存修改
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 表单验证和防止重复提交
(function() {
    'use strict';
    const form = document.querySelector('form');
    const submitBtn = document.getElementById('submitBtn');
    
    // Bootstrap表单验证
    form.addEventListener('submit', function(event) {
        if (!form.checkValidity()) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            if (submitBtn.disabled) {
                event.preventDefault();
                return;
            }
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
        }
        
        form.classList.add('was-validated');
    });
})();

// 图片预览功能
document.getElementById('order_screenshot').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            // 移除旧的预览
            const oldPreview = document.querySelector('#screenshotPreview');
            if (oldPreview) oldPreview.remove();
            
            // 创建新的预览
            const previewDiv = document.createElement('div');
            previewDiv.id = 'screenshotPreview';
            previewDiv.className = 'mt-2';
            previewDiv.innerHTML = `
                <label class="form-label">新截图预览：</label>
                <div>
                    <img src="${e.target.result}" class="img-thumbnail" style="max-height: 200px; cursor: pointer;"
                         onclick="openImageModal('${e.target.result}')">
                    <div class="form-text">点击图片查看大图</div>
                </div>
            `;
            
            // 插入到文件输入框后面
            const fileInput = document.getElementById('order_screenshot');
            fileInput.parentNode.insertBefore(previewDiv, fileInput.nextSibling);
        };
        reader.readAsDataURL(file);
    }
});
</script>

<?php include __DIR__ . '/footer.php'; ?>